import React from 'react'
import Meal from './Meal/Meal'
import Classes from './Meals.module.css'
import TestContext from '../../store/TestContext'
import TestB from '../TestB/TestB'
import TestA from '../TestA/Test'
const _mealsData = [
  {
    id: 1,
    title: '汉堡包',
    desc: '百分百纯牛肉配搭爽口莴笋丝，搭配上冰山egd®双层香roller大rostllaordered，',
    price: 12,
    img: '/img/meals/1.png'
  },
  {
    id: 2,
    title: '双层牛肉汉堡',
    desc: '百分百纯牛肉配搭爽口莴笋丝，搭配上冰山egd®双层香roller大rostllaordered，',
    price: 20,
    img: '/img/meals/2.png'
  },
  {
    id: 3,
    title: '巨无霸',
    desc: '两块烤牛肉饼，三片芝士，生菜，酸黄瓜，洋葱，特制酱汁，夹在芝麻面包中。',
    price: 24,
    img: '/img/meals/3.png'
  },
  {
    id: 4,
    title: '麦辣鸡腿堡',
    desc: '麦辣鸡腿堡是麦当劳的招牌汉堡之一，深受广大消费者喜爱。',
    price: 21,
    img: '/img/meals/4.png'
  },
  {
    id: 5,
    title: '板烧鸡腿堡',
    desc: '板烧鸡腿堡',
    price: 21,
    img: '/img/meals/5.png'
  },
  {
    id: 6,
    title: '麦辣鸡腿堡',
    desc: '麦辣鸡腿堡是麦当劳的招牌汉堡之一，深受广大消费者喜爱。',
    price: 21,
    img: '/img/meals/6.png'
  },
  {
    id: 7,
    img: '/img/meals/7.png',
    title: '麦辣鸡腿堡',
    price: 12,
    desc: '麦辣鸡腿堡是麦当劳的招牌汉堡之一，深受广大消费者喜爱。'
  }
]
const Meals = () => {
  const [mealsData, setMealsData] = React.useState(_mealsData)
  const [cartData, setCartData] = React.useState({
    totalPrice: 0,
    totalAmount: 0,
    goods: []
  })
  const addMealHandeler = meal => {
    const newCartData = { ...cartData }
    const index = newCartData.goods.findIndex(item => item.id === meal.id)
    if (index === -1) {
      meal.amount = 1
      newCartData.goods.push(meal)
    } else {
        meal.amount += 1
    }
    newCartData.totalAmount++
    newCartData.totalPrice += meal.price
    setCartData(newCartData)
  }
  const removeMealHandeler = meal => {
    const newCartData  ={...cartData}
    if(meal.amount === 1){
        meal.amount = 0
        newCartData.goods.splice(newCartData.goods.findIndex(item=>item.id === meal.id),1)
    }else{
        meal.amount -= 1
    }
    newCartData.totalAmount--
    newCartData.totalPrice -= meal.price
    setCartData(newCartData)
  }
//   Context 会读取距离最近的Provider提供的数据 如果没有
  return (
    <TestContext.Provider value={{ add: addMealHandeler, sub: removeMealHandeler }}>
      <div className={Classes.Meals}>
        {mealsData.map(item => {
          return (
            <Meal
              key={item.id}
              meal={item}
            ></Meal>
          )
        })}
      </div>
    </TestContext.Provider>
  )
}
export default Meals
